<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/statistics' }"
        >账单统计</el-breadcrumb-item
      >
      <el-breadcrumb-item>基金管理</el-breadcrumb-item>
    </el-breadcrumb>

    <el-card>
      <!-- 搜索与添加区域 -->
      <el-row :gutter="20">
        <el-col :span="6">
          <el-input
            placeholder="请输入基金名称"
            v-model="queryInfo.fundName"
            clearable
            @clear="getFunds"
          >
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="getFunds"
            ></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button
            type="primary"
            @click="addDialogVisible = true"
            v-show="addButton"
            >添加基金</el-button
          >
        </el-col>
      </el-row>

      <el-divider></el-divider>

      <!-- 用户列表区域 -->
      <el-table
        :data="fundList"
        border
        stripe
        :header-cell-style="{ 'text-align': 'center' }"
        :cell-style="{ 'text-align': 'center' }"
      >
        <el-table-column type="index" fixed></el-table-column>
        <el-table-column
          fixed
          label="姓名"
          prop="username"
          min-width="40%"
        ></el-table-column>
        <el-table-column
          label="基金名称"
          prop="fundName"
          fixed
        ></el-table-column>
        <el-table-column label="购买金额" prop="buyMoney"></el-table-column>
        <el-table-column label="目前金额" prop="currentMoney"></el-table-column>
        <el-table-column
          label="是否封闭"
          prop="status"
          :formatter="statusFormat"
        ></el-table-column>
        <el-table-column
          label="位置"
          prop="location"
          :formatter="locationFormat"
        ></el-table-column>
        <el-table-column
          label="本月盈利"
          prop="profit"
          min-width="120%"
        ></el-table-column>
        <el-table-column
          label="购买时间"
          prop="buyTime"
          min-width="120%"
        ></el-table-column>
        <el-table-column
          label="封闭到期时间"
          prop="expirationTime"
          min-width="120%"
        ></el-table-column>
        <el-table-column label="卖出金额" prop="sellMoney"></el-table-column>
        <el-table-column
          label="更新时间"
          prop="updateTime"
          :formatter="formatDate"
          min-width="120%"
        ></el-table-column>
        <el-table-column label="状态" prop="del">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.del"
              @change="updateDel(scope.row)"
              :active-value="1"
              :inactive-value="0"
            >
            </el-switch>
          </template>
        </el-table-column>

        <el-table-column label="操作" width="180px" fixed="right">
          <template slot-scope="scope">
            <!-- 修改按钮 -->
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="showEditDialog(scope.row.id)"
            ></el-button>
            <!-- 删除按钮 -->
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="removeFundById(scope.row.id)"
            ></el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页区域 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pageNum"
        :page-sizes="[1, 2, 5, 10]"
        :page-size="queryInfo.pageSize"
        layout="->,total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>

    <!-- 添加基金的对话框 -->
    <el-dialog
      title="添加基金"
      :visible.sync="addDialogVisible"
      width="50%"
      @close="addDialogClosed"
    >
      <el-divider></el-divider>
      <!-- 内容主体区域 -->
      <el-form
        :model="addForm"
        :rules="addFormRules"
        ref="addFormRef"
        label-width="80px"
        size="mini"
      >
        <el-form-item label="基金名称" prop="fundName">
          <el-input
            v-model="addForm.fundName"
            placeholder="请输入基金名称"
          ></el-input>
        </el-form-item>
        <el-form-item label="购买金额" prop="buyMoney">
          <el-input
            v-model="addForm.buyMoney"
            placeholder="请输入购买金额"
          ></el-input>
        </el-form-item>
        <el-form-item label="售卖金额" prop="sellMoney">
          <el-input
            v-model="addForm.sellMoney"
            placeholder="请输入售卖金额"
          ></el-input>
        </el-form-item>
        <el-form-item label="本月盈利" prop="profit">
          <el-input
            v-model="addForm.profit"
            placeholder="请输入目前金额"
          ></el-input>
        </el-form-item>
        <el-form-item label="是否封闭" prop="status">
          <el-switch
            v-model="addForm.status"
            :active-value="2"
            :inactive-value="1"
          ></el-switch>
        </el-form-item>
        <el-form-item label="基金位置">
          <el-radio-group v-model="addForm.location">
            <el-radio :label="1">微信</el-radio>
            <el-radio :label="2">支付宝</el-radio>
            <el-radio :label="3">其他</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="购买时间" required>
          <el-col :span="20">
            <el-col :span="10">
              <el-form-item prop="buyTime1"
                ><el-date-picker
                  type="date"
                  placeholder="选择日期"
                  v-model="addForm.buyTime1"
                  style="width: 90%"
                  editable
                  value-format="yyyy-MM-dd"
                ></el-date-picker
              ></el-form-item>
            </el-col>
            <el-col class="line" :span="1">-</el-col>
            <el-col :span="10"
              ><el-form-item prop="buyTime2"
                ><el-time-picker
                  placeholder="选择时间"
                  v-model="addForm.buyTime2"
                  style="width: 90%"
                  editable
                  value-format="HH:mm:ss"
                ></el-time-picker></el-form-item
            ></el-col>
          </el-col>
        </el-form-item>
        <el-form-item label="售卖时间" required>
          <el-col :span="20">
            <el-col :span="10">
              <el-form-item prop="sellTime1"
                ><el-date-picker
                  type="date"
                  placeholder="选择日期"
                  v-model="addForm.sellTime1"
                  style="width: 90%"
                  editable
                  value-format="yyyy-MM-dd"
                ></el-date-picker
              ></el-form-item>
            </el-col>
            <el-col class="line" :span="1">-</el-col>
            <el-col :span="10"
              ><el-form-item prop="sellTime2"
                ><el-time-picker
                  placeholder="选择时间"
                  v-model="addForm.sellTime2"
                  style="width: 90%"
                  editable
                  value-format="HH:mm:ss"
                ></el-time-picker></el-form-item
            ></el-col>
          </el-col>
        </el-form-item>
      </el-form>
      <!-- 底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="addFund">确 定</el-button>
        <el-button @click="addDialogVisible = false">取 消</el-button>
      </span>
    </el-dialog>

    <!-- 更新基金的对话框 -->
    <el-dialog
      title="更新基金"
      :visible.sync="editDialogVisible"
      width="50%"
      @close="editDialogClosed"
    >
      <el-divider></el-divider>
      <!-- 内容主体区域 -->
      <el-form
        :model="editForm"
        :rules="editFormRules"
        ref="editFormRef"
        label-width="80px"
        size="mini"
      >
        <el-form-item label="基金名称" prop="fundName">
          <el-input v-model="editForm.fundName" disabled></el-input>
        </el-form-item>
        <el-form-item label="购买金额" prop="buyMoney">
          <el-input v-model="editForm.buyMoney"></el-input>
        </el-form-item>
        <el-form-item label="售卖金额" prop="sellMoney">
          <el-input v-model="editForm.sellMoney"></el-input>
        </el-form-item>
        <el-form-item label="本月盈利" prop="profit">
          <el-input v-model="editForm.profit"></el-input>
        </el-form-item>
        <el-form-item label="是否封闭" prop="status">
          <el-switch
            v-model="editForm.status"
            :active-value="2"
            :inactive-value="1"
          ></el-switch>
        </el-form-item>

        <el-form-item label="售卖时间">
          <el-col :span="20">
            <el-col :span="10">
              <el-form-item prop="sellTime1"
                ><el-date-picker
                  type="date"
                  placeholder="选择日期"
                  v-model="editForm.sellTime1"
                  style="width: 90%"
                  editable
                  value-format="yyyy-MM-dd"
                ></el-date-picker
              ></el-form-item>
            </el-col>
            <el-col class="line" :span="1">-</el-col>
            <el-col :span="10"
              ><el-form-item prop="sellTime2"
                ><el-time-picker
                  placeholder="选择时间"
                  v-model="editForm.sellTime2"
                  style="width: 90%"
                  editable
                  value-format="HH:mm:ss"
                ></el-time-picker></el-form-item
            ></el-col>
          </el-col>
        </el-form-item>
      </el-form>
      <!-- 底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="editFund">确 定</el-button>
        <el-button @click="editDialogVisible = false">取 消</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      total: 0,
      queryInfo: {
        fundName: '',
        // 当前的页数
        pageNum: 1,
        // 当前每页显示多少条数据
        pageSize: 10,
        userId: window.sessionStorage.getItem('token'),
        startTime: '',
        endTime: ''
      },

      fundList: [],
      // 控制添加用户对话框的显示与隐藏
      addDialogVisible: false,
      editDialogVisible: false,
      // 添加基金的表单数据
      addForm: {
        userId: window.sessionStorage.getItem('token'),
        fundName: '',
        buyMoney: '',
        sellMoney: '',
        profit: '',
        status: 2,
        location: 1,
        buyTime: '',
        buyTime1: '',
        buyTime2: '',
        sellTime: '',
        sellTime1: '',
        sellTime2: '',
        del: 1
      },
      // 添加表单的验证规则对象
      addFormRules: {
        fundName: [
          { required: true, message: '请输入基金名称', trigger: 'blur' },
          {
            min: 0,
            max: 50,
            message: '基金的长度在0~50个字符之间',
            trigger: 'blur'
          }
        ],
        buyMoney: [
          { required: true, message: '请输入购买金额', trigger: 'blur' }
        ],
        profit: [
          { required: true, message: '请输入本月盈利', trigger: 'blur' }
        ],
        buyTime1: [
          {
            required: true,
            type: 'string',
            message: '请选择日期',
            trigger: 'blur'
          }
        ],
        buyTime2: [
          {
            required: true,
            type: 'string',
            message: '请选择时间',
            trigger: 'blur'
          }
        ],
        sellTime1: [
          {
            required: true,
            type: 'string',
            message: '请选择日期',
            trigger: 'blur'
          }
        ],
        sellTime2: [
          {
            required: true,
            type: 'string',
            message: '请选择时间',
            trigger: 'blur'
          }
        ]
      },
      editForm: {
        id: '',
        userId: window.sessionStorage.getItem('token'),
        fundName: '',
        buyMoney: '',
        sellMoney: '',
        profit: '',
        status: 2,
        sellTime: '',
        sellTime1: '',
        sellTime2: ''
      },
      editFormRules: {
        profit: [{ required: true, message: '请输入本月盈利', trigger: 'blur' }]
      }
    }
  },
  created() {
    this.getFunds()
  },
  computed: {
    addButton() {
      return window.sessionStorage.getItem('token') !== '-1'
    }
  },
  methods: {
    // 获取所有的金额
    async getFunds() {
      const { data: res } = await this.$http.get('/fund', {
        params: this.queryInfo
      })
      if (res.code !== 1) {
        return this.$message.error('获取所有基金失败！')
      }
      this.fundList = res.data.pageList
      console.log(this.fundList)
      this.total = res.data.total
    },

    // 删除基金
    async removeFundById(id) {
      const { data: res } = await this.$http.delete('/fund', {
        params: { ids: id }
      })
      if (res.code !== 1) {
        return this.$message.error('删除基金失败！')
      }
      this.$message.success('删除基金成功！')
      this.getFunds()
    },
    // 更新状态
    async updateDel(fund) {
      console.log(fund)
      const { data: res } = await this.$http.post('/fund/updateDel/', fund)
      console.log(res)
      if (res.code !== 1) {
        return this.$message.error('更新基金状态失败！')
      }
      this.getFunds()
    },

    // 添加基金
    // 这里先不添加async
    // async addFund() {
    addFund() {
      this.$refs.addFormRef.validate(async (valid) => {
        if (!valid) {
          this.$message.warning('必填项不能为空')
          return
        }

        this.addForm.buyTime =
          this.addForm.buyTime1 + ' ' + this.addForm.buyTime2

        this.addForm.sellTime =
          this.addForm.sellTime1 + ' ' + this.addForm.sellTime2

        const { data: res } = await this.$http.post('fund', this.addForm)

        if (res.code !== 1) {
          return this.$message.error('添加基金失败！')
        }

        this.$message.success('添加基金成功！')
        // 隐藏添加用户的对话框
        this.addDialogVisible = false
        this.$refs.addFormRef.resetFields()
        // 重新获取用户列表数据
        this.getFunds()
      })
    },

    editFund() {
      this.$refs.editFormRef.validate(async (valid) => {
        if (!valid) {
          this.$message.warning('必填项不能为空')
          return
        }

        if (this.editForm.sellTime1 && this.editForm.sellTime2) {
          this.editForm.sellTime =
            this.editForm.sellTime1 + ' ' + this.editForm.sellTime2
        }

        this.editForm.userId = window.sessionStorage.getItem('token')

        console.log(this.editForm)
        const { data: res } = await this.$http.post(
          '/fund/updateFund',
          this.editForm
        )

        if (res.code !== 1) {
          this.$message.error('更新基金失败！')
        }

        this.$message.success('更新基金成功！')
        // 隐藏添加用户的对话框
        this.editDialogVisible = false
        this.$refs.editFormRef.resetFields()
        // 重新获取用户列表数据
        this.getFunds()
      })
    },

    async showEditDialog(id) {
      const { data: res } = await this.$http.get('/fund/getFundById/' + id)

      if (res.code !== 1) {
        return this.$message.error('查询基金失败！')
      }

      this.editForm = res.data
      this.editDialogVisible = true
    },

    // 是否封闭数字翻译中文
    statusFormat(row, column) {
      return row.status === '1' ? '是' : '否'
    },

    // 位置数字翻译中文
    locationFormat(row, column) {
      if (row.location === 1) {
        return '微信'
      } else if (row.location === 2) {
        return '支付宝'
      } else {
        return '其他'
      }
    },

    // 监听添加用户对话框的关闭事件
    addDialogClosed() {
      this.$refs.addFormRef.resetFields()
    },
    // 监听修改用户对话框的关闭事件
    editDialogClosed() {
      this.$refs.editFormRef.resetFields()
    },

    formatDate(row, column, cellValue, index) {
      if (cellValue != null) {
        var date = new Date(cellValue)
        var year = date.getFullYear()
        /* 在日期格式中，月份是从0开始，11结束，因此要加0
         * 使用三元表达式在小于10的前面加0，以达到格式统一  如 09:11:05
         * */
        var month =
          date.getMonth() + 1 < 10
            ? '0' + (date.getMonth() + 1)
            : date.getMonth() + 1
        var day = date.getDate() < 10 ? '0' + date.getDate() : date.getDate()
        var hours =
          date.getHours() < 10 ? '0' + date.getHours() : date.getHours()
        var minutes =
          date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()
        var seconds =
          date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds()
        // 拼接
        return (
          year +
          '-' +
          month +
          '-' +
          day +
          ' ' +
          hours +
          ':' +
          minutes +
          ':' +
          seconds
        )
      }
    },

    // 监听 pagesize 改变的事件
    handleSizeChange(newSize) {
      // console.log(newSize)
      this.queryInfo.pageSize = newSize
      this.getFunds()
    },
    // 监听 页码值 改变的事件
    handleCurrentChange(newPage) {
      console.log(newPage)
      this.queryInfo.pageNum = newPage
      this.getFunds()
    }
  }
}
</script>

<style lang="less" scoped>
.el-form .el-form-item .el-input {
  width: 240px;
}

.el-form {
  margin-left: 100px;
}
/deep/.el-dialog .el-dialog__footer {
  text-align: center;
  margin-top: -25px;
}
.el-dialog .el-divider {
  margin-top: -25px;
}
</style>
